package com.unicom.springhw;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unicom.springhw.entiy.PhotoPo;
import com.unicom.springhw.until.PhotoMake;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

@Slf4j
@Controller
public class UploadController {
    @Autowired
    public PhotoPo photoPo;
    String URL="https://alidphoto.aisegment.com/idphoto/make";
    private final String AppKey = "你的阿里AppKey"; // 请注意了，AppKey和AppCode不是同一个东西
    private final String AppSecret = "你的阿里secret";
    @RequestMapping("/up")
    public ModelAndView tzupload() {
        log.info("跳转uplaod页面");
        return new ModelAndView("/upload.html");
    }

    @ResponseBody
    @PostMapping("/uploads")
    public String upload(
            @RequestPart("head_img") MultipartFile headerImg
    ) throws IOException {

        log.info("上传的信息：headerImg={}",
                headerImg.getSize());

        if (!headerImg.isEmpty()) {
            //保存到文件服务器，OSS服务器
            String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("E:\\cache\\" + originalFilename));
            //请求转换证件照
            PhotoMake idmake=new PhotoMake();
            File imageFile =new File("E:/cache/"+originalFilename);
            File dstFile = new File("E:/cache/");
            byte[] buffer = idmake.resizeAndReadImage(imageFile);
            if (buffer == null) {
                return null;
            }
            HttpHeaders httpHeader=new HttpHeaders();
            httpHeader.setContentType(MediaType.APPLICATION_JSON);
            httpHeader.set("X-Ca-Key", this.AppKey);
            PhotoMake photoMake=new PhotoMake();
            // BASE64Encoder b64Encoder = new BASE64Encoder();
            String imageBase64 = this.base64(buffer);
            String fileName = imageFile.getName();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
            String photoType = fileExt.replace(".", "");
            photoPo.setType(photoType);
            photoPo.setPhoto(imageBase64);
            photoPo.setSpec("1");
            photoPo.setBk("red");
            photoPo.setBeauty_degree(3.0F);
            String requestJson= JSON.toJSONString(photoPo);
            HttpEntity<String> httpEntity=new HttpEntity<String>(requestJson,httpHeader);
            String result=this.getRespones(URL,httpEntity);
            if (result == null) {
                return "转换错误";
            }else{
                JSONObject jsonmsg=JSON.parseObject(result);
               int reslutCode=jsonmsg.getIntValue("status");
               if(reslutCode==0){
                   JSONObject data=jsonmsg.getJSONObject("data");
                   String downUrl=data.getString("result");
                   PhotoMake.downloadFromUrl(downUrl,dstFile);

               }
            }





        }

        return "上传成功";
    }
    @ResponseBody
    @RequestMapping("/download")
    public String download(@RequestParam String filename,HttpServletResponse response) throws IOException{
        String urladdress = "https://oapi.aisegment.com/static/photo/p2/20210716/result/f3e/f3e07e1fef22412a948aac7cef07a860.jpg";
        URL url=new URL(urladdress);
        URLConnection conn=url.openConnection();
        InputStream inputStream= conn.getInputStream();
        byte[] buffer=new byte[1024];
        int len=0;
        OutputStream outputStream= null;
  //      response.setHeader("content-type", "image/jpg");
        response.setContentType("image/jpg");
        response.setHeader("content-disposition","attachment;filename="+java.net.URLEncoder.encode(filename,"UTF-8") +".jpg");
        try {
            outputStream = response.getOutputStream();
            while((len=inputStream.read(buffer))>0){
                outputStream.write(buffer,0, len);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "下载成功";
    }


    public String getRespones(String url,HttpEntity<String> photoPo){
        RestTemplate restTemplate = new RestTemplate();
        String msg=restTemplate.postForObject(url, photoPo,String.class);
        return msg;

    }

    public String base64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }


}
